package com.daydayup.mine;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * 扫雷
 * 
 * @author Administrator
 *
 */
public class MineSweeper {

	private String[][] squares;

	/**
	 * 初始化，用^代表
	 */
	public void init(Integer rows, Integer columns) {
		squares = new String[rows][columns];
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				squares[i][j] = "^";
			}
		}
		// print(squares);
	}

	/**
	 * 
	 * @param firstRow
	 *            第一个雷的行数
	 * @param firstColumn
	 *            第一个雷的列数
	 * @param count
	 *            雷的数量
	 */
	public void createMines(Integer rows, Integer columns, Integer firstRow, Integer firstColumn, Integer count) {
		// 雷的数量不能大于总的位置数量
		if (rows * columns <= count) {
			throw new MineException("你雷的数量太多了");
		}
		Set<Mine> mines = new HashSet<>();
		Random random = new Random();
		while (mines.size() != count) {
			int minRow = random.nextInt(rows); // 生成0~行数之间的随机数
			int mincolumn = random.nextInt(columns);
			if (minRow == firstRow - 1 && mincolumn == firstColumn - 1) {
				continue;
			}
			// 将此时的雷标记为*
			squares[minRow][mincolumn] = "*";
			Mine mine = new Mine();
			mine.setRow(minRow);
			mine.setColumn(mincolumn);
			mines.add(mine);
		}

	}

	/**
	 * 计算周围雷的数量
	 * 
	 * @param row
	 * @param column
	 * @return
	 */
	public void calculateMineCount(Integer row, Integer column, int rows, int columns) {
		// 如果此颗是雷，结束游戏
		if (squares[row - 1][column - 1] == "*") {
			System.out.println("===========踩到雷了，游戏结束！===========");
			throw new MineException("===========踩到雷了，游戏结束！===========");
		}
		int rowTemp = row;
		int count = 0;
		rowTemp = rowTemp - 2;
		for (int i = 0; i <= 2; i++) {
			if (rowTemp >= 0 && rowTemp < rows) {
				int columnTemp = column;
				columnTemp = columnTemp - 2;
				for (int j = 0; j <= 2; j++) {
					if (columnTemp >= 0 && columnTemp < columns) {
						if (squares[rowTemp][columnTemp] == "*") {
							count += 1;
						}
					}
					columnTemp += 1;
				}
			}
			rowTemp += 1;
		}
		squares[row - 1][column - 1] = count + "";
		print(squares, rows, columns);
	}

	private void print(String[][] squares, int rows, int columns) {
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				if (squares[i][j] == "*") {
					System.out.print("^ ");
				} else {
					System.out.print(squares[i][j] + " ");
				}
			}
			System.out.println();
		}
	}

}
